import { createPinia, defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 创建Pinia实例
 */
const pinia = createPinia()

/**
 * 用户状态管理
 * 管理用户信息、登录状态等
 */
export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref('')
  const userInfo = ref({
    id: '',
    username: '',
    avatar: ''
  })

  // 计算属性
  const isLoggedIn = computed(() => Boolean(token.value))

  // 操作方法
  function setToken(newToken: string) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  function setUserInfo(info: typeof userInfo.value) {
    userInfo.value = info
  }

  function logout() {
    token.value = ''
    userInfo.value = {
      id: '',
      username: '',
      avatar: ''
    }
    localStorage.removeItem('token')
  }

  // 初始化
  function init() {
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      token.value = savedToken
      // 这里可以添加获取用户信息的逻辑
    }
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    setToken,
    setUserInfo,
    logout,
    init
  }
})

/**
 * 应用设置状态管理
 * 管理应用主题、语言等全局设置
 */
export const useAppStore = defineStore('app', () => {
  // 状态
  const theme = ref('light')
  const language = ref('zh-CN')

  // 操作方法
  function setTheme(newTheme: 'light' | 'dark') {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
  }

  function setLanguage(newLang: string) {
    language.value = newLang
    localStorage.setItem('language', newLang)
  }

  // 初始化
  function init() {
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
      theme.value = savedTheme as 'light' | 'dark'
    }
    
    const savedLang = localStorage.getItem('language')
    if (savedLang) {
      language.value = savedLang
    }
  }

  return {
    theme,
    language,
    setTheme,
    setLanguage,
    init
  }
})

export default pinia